package cn.jingzhuan.fm.ui.fragment;

import android.content.Context;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;

import cn.jingzhuan.fm.ui.BaseFragment;


public abstract class BaseBindingFragment<T extends ViewDataBinding> extends BaseFragment {

    protected T mBinding;
    protected QMUITipDialog mProgressDialog;
    private OnAfterDataBindListener mAfterDataBindListener;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {

        View rootView = inflater.inflate(getLayoutId(), container, false);
        mBinding = createDataBinding(rootView);
        this.onDataBind(savedInstanceState, mBinding);

        if (mAfterDataBindListener != null) {
            mAfterDataBindListener.onDataBind(getContext());
        }
        return rootView;
    }

    public T createDataBinding(View rootView) {
        return DataBindingUtil.bind(rootView);
    }

    @Override public void onDestroyView() {
        super.onDestroyView();
        mBinding.unbind();
    }

    protected abstract void onDataBind(@Nullable Bundle savedInstanceState, T binding);

    @LayoutRes
    protected abstract int getLayoutId();

    protected void showProgress(String msg) {
        if (getContext() != null) {
            if (mProgressDialog != null) mProgressDialog.dismiss();

            mProgressDialog = new QMUITipDialog.Builder(getContext())
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                .setTipWord(msg)
                .create();
            mProgressDialog.setCancelable(true);
            mProgressDialog.show();
        }
    }

    protected void showProgress() {
        showProgress("正在加载");
    }

   protected void hideProgress(){
       if (mProgressDialog != null && mProgressDialog.isShowing()) {
           mProgressDialog.dismiss();
       }
   }


    public void setAfterDataBindListener(OnAfterDataBindListener afterDataBindListener) {
        this.mAfterDataBindListener = afterDataBindListener;
    }

    public interface OnAfterDataBindListener {
       void onDataBind(Context context);
   }

}
